package com.appbee.lyrdb.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LyrDbClient
{
	private static final Logger log = Logger.getLogger(LyrDbClient.class.getName());
	public List<LyrSong> findByFullt(String q) throws Exception
	{
		ArrayList<LyrSong> list = new ArrayList<LyrSong>();
		try
		{
			URL url = new URL(
					"http://webservices.lyrdb.com/lookup.php?for=fullt&agent=agent&q="
							+ URLEncoder.encode(q, "UTF-8"));
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String line;

			while ((line = reader.readLine()) != null)
			{
				String[] split = line.split("\\\\");
				if(split.length>2)
				{
					LyrSong song = new LyrSong();
					song.setId(split[0]);
					song.setName(split[1]);
					song.setArtist(split[2]);
					list.add(song);
				}
				else
				{
					log.log(Level.SEVERE,"Unexpected format in LyrSong line: "+line);
				}
			}
			reader.close();
			log.info("Size: " + list.size());
			return list;

		}
		catch (MalformedURLException e)
		{
			throw e;
		}
		catch (IOException e)
		{
			throw e;
		}
	}
	
	public String findFirstByFullt(String q)
	throws Exception
	{
		List<LyrSong> list = findByFullt(q);
		if(list.size()>0)
		{
			LyrSong song = list.get(0);
			return findById(song.getId());
		}
		return "";
	}
	
	public String findById(String lyricId)
	throws Exception
	{
		try
		{
			URL url = new URL(
					"http://www.lyrdb.com/getlyr.php?q="
							+ URLEncoder.encode(lyricId, "UTF-8"));
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			StringBuffer result = new StringBuffer();
			String line;

			while ((line = reader.readLine()) != null)
			{
				result.append(line);
				result.append("<br>");
			}
			reader.close();
			return result.toString();

		}
		catch (MalformedURLException e)
		{
			throw e;
		}
		catch (IOException e)
		{
			throw e;
		}
		
	}
}
